<template>
  <div>
    <x-header :left-options="{ showBack: false }" :right-options="{ showMore: true }" @on-click-more="showMenus = true"
      >投票一览</x-header
    >
    <div class="mh-scroller-box">
      <scroller :on-refresh="refresh" :on-infinite="infinite" ref="item_scroller">
        <main class="mh-scroller-content">
          <div v-for="(item, i) in items" :key="i" class="mh-item" @click="handleOptions(item.voteId)">
            <flexbox orient="vertical">
              <flexbox-item>
                <h2>{{ item.voteName }}</h2>
              </flexbox-item>
              <flexbox-item>
                <p>{{ item.description }}</p>
              </flexbox-item>
              <flexbox-item>
                <flexbox>
                  <flexbox-item :span="4">结束时间</flexbox-item>
                  <flexbox-item :span="8">{{ item.endDate }}</flexbox-item>
                </flexbox>
              </flexbox-item>
              <flexbox-item>
                <flexbox>
                  <flexbox-item :span="4">是否投票</flexbox-item>
                  <flexbox-item :span="8">
                    <div v-if="item.voted">
                      <icon type="success"></icon>
                    </div>
                    <div v-else>
                      <icon type="circle"></icon>
                    </div>
                  </flexbox-item>
                </flexbox>
              </flexbox-item>
            </flexbox>
          </div>
        </main>
      </scroller>
      <mh-tabbar :badge="unhandleVoteCount.toString()" selectedKey="vote_list"></mh-tabbar>
    </div>
    <div v-transfer-dom>
      <popup v-model="showOptions" height="90%">
        <div class="mh-popup-docs">
          <div>
            <x-button @click.native="handleVote" type="primary">立即投票</x-button>
          </div>
          <div>
            <x-textarea
              :max="200"
              :rows="5"
              placeholder="请输入您的选择该选项的原因"
              v-model="voteDescription"
            ></x-textarea>
          </div>
          <div v-for="(option, i) in options" :key="i" class="mh-item">
            <div @click="checkOption(option.optionId)">
              <flexbox orient="vertical">
                <flexbox-item>
                  <h2>
                    <check-icon :value.sync="option.checked"> {{ option.optionName }}</check-icon>
                  </h2>
                </flexbox-item>
                <flexbox-item>
                  <p>{{ option.description }}</p>
                </flexbox-item>
              </flexbox>
            </div>
            <div>
              <x-button
                type="primary"
                v-clipboard:copy="option.description"
                v-clipboard:success="onCopy"
                v-clipboard:error="onCopyError"
              >
                复制
              </x-button>
            </div>
          </div>
        </div>
      </popup>
    </div>
    <div v-transfer-dom>
      <popup v-model="showSearch" height="90%">
        <div class="mh-popup-docs">
          <flexbox>
            <flexbox-item>
              <div>
                <x-input title="关键字" v-model="keyword" placeholder="请输入关键字"></x-input>
              </div>
              <div>
                <x-button @click.native="handleSearch" type="primary">立即搜索</x-button>
              </div>
              <div>
                <x-switch title="关闭查询框" v-model="showSearch"></x-switch>
              </div>
            </flexbox-item>
          </flexbox>
        </div>
      </popup>
    </div>
    <div v-transfer-dom>
      <actionsheet @on-click-menu="clickActionsheet" :menus="menus" v-model="showMenus" show-cancel></actionsheet>
    </div>
  </div>
</template>
<script>
import Api from '@/libs/api'
import qs from 'qs'
import MhTabbar from './MhTabbar'
import Vue from 'vue'
import {
  Popup,
  XInput,
  XSwitch,
  XButton,
  Tabbar,
  TabbarItem,
  TransferDom,
  Flexbox,
  FlexboxItem,
  Actionsheet,
  Divider,
  CheckIcon,
  Icon,
  XTextarea
} from 'vux'
export default {
  directives: {
    TransferDom
  },
  components: {
    'mh-tabbar': MhTabbar,
    Popup,
    XInput,
    XSwitch,
    XButton,
    Tabbar,
    TabbarItem,
    Actionsheet,
    Divider,
    Flexbox,
    FlexboxItem,
    CheckIcon,
    Icon,
    XTextarea
  },
  data() {
    return {
      noMore: false,
      items: [],
      options: [],
      page: 0,
      pageSize: 5,
      keyword: '',
      menus: {
        menuSearch: '搜索投票',
        menuLogout: '退出登录'
      },
      showMenus: false,
      showSearch: false,
      showOptions: false,
      voteDescription: '',
      unhandleVoteCount: ''
    }
  },
  mounted: function() {},
  methods: {
    onCopy: function(e) {
      Vue.$vux.toast.show({
        text: '复制成功',
        position: 'middle',
        type: 'success'
      })
      console.log('你刚刚复制: ' + e.text)
    },
    onCopyError: function(e) {
      console.log('无法复制文本！')
    },
    checkOption(optionId) {
      for (let index = 0; index < this.options.length; index++) {
        const option = this.options[index]
        if (option.optionId === optionId) {
          this.options[index].checked = true
        } else {
          this.options[index].checked = false
        }
      }
    },
    clickActionsheet(key) {
      if (key === 'menuSearch') {
        this.showSearch = true
      }
      if (key === 'menuLogout') {
        this.$store.commit('changeToken', null)
        this.$store.commit('changeUser', null)
        this.$router.push({
          name: 'login'
        })
      }
    },
    handleSearch() {
      this.showSearch = false
      this.refresh()
    },
    handleVote() {
      let countChecked = 0
      let optionId = null
      for (let index = 0; index < this.options.length; index++) {
        const option = this.options[index]
        if (option.checked) {
          countChecked++
          optionId = option.optionId
        }
      }
      if (countChecked === 1) {
        var that = this
        let params = {
          token: this.$store.state.token,
          description: this.voteDescription
        }
        Api.http
          .post(Api.ajaxBaseUrl + `/api/home/options/${optionId}/check`, params)
          .then(function(result) {
            if (result.code === 0) {
              that.showOptions = false
              that.refresh()
            }
          })
          .catch(function(message) {})
      } else {
        Vue.$vux.toast.show({
          text: '请选择您要投票的选项',
          position: 'middle',
          type: 'warn'
        })
      }
    },
    handleOptions(voteId) {
      this.showOptions = true
      this.voteDescription = ''
      this.getOptions(voteId)
    },
    refresh() {
      this.page = 1
      this.noMore = false
      this.getData()
    },
    infinite: function(done) {
      if (this.noMore) {
        done(true)
        this.$refs.item_scroller.finishInfinite(true)
      } else {
        this.page++
        var that = this
        that.getData(done)
      }
    },
    // 获取数据，由于是http异步，所以done要放在回调中执行
    getData(done) {
      var that = this
      let params = qs.stringify({
        token: this.$store.state.token,
        page: this.page,
        rows: this.pageSize,
        title: this.keyword
      })
      Api.http
        .get(Api.url.list + '?' + params)
        .then(function(result) {
          if (result.code === 0) {
            if (that.page === 1) {
              that.items = result.items
            } else {
              that.items = that.items.concat(result.items)
            }
            // 统计未处理的投票数
            that.unhandleVoteCount = 0
            for (let index = 0; index < that.items.length; index++) {
              const vote = that.items[index]
              if (!vote.voted) {
                that.unhandleVoteCount++
              }
            }
            if (that.unhandleVoteCount === 0) {
              that.unhandleVoteCount = ''
            }
            // 这里通过done判断到底是不是refresh操作
            if (typeof done !== 'function') {
              that.$refs.item_scroller.finishPullToRefresh()
            }
            if (result.total <= that.page) {
              // 最后一页没有数据了
              that.noMore = true
              // 判断是infinite
              if (typeof done === 'function') {
                done(true)
                this.$refs.item_scroller.finishInfinite(true)
              }
            } else {
              that.noMore = false
              // 判断是infinite
              if (typeof done === 'function') {
                done()
              }
            }
          }
        })
        .catch(function(message) {})
    },
    getOptions(voteId) {
      var that = this
      let params = qs.stringify({
        token: this.$store.state.token
      })
      Api.http
        .get(Api.ajaxBaseUrl + `/api/home/votes/${voteId}/options` + '?' + params)
        .then(function(result) {
          if (result.code === 0) {
            that.options = result.items
          }
        })
        .catch(function(message) {})
    }
  }
}
</script>
<style>
@import '../style/main.less';
</style>
